import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class PainelChat {
	
	private JPanel chatPane;
	private JTextArea chatText;
	private PrintStream saida;
	private Socket cliente;
	private JTextField chatLine;
	public static StringBuffer toSend = new StringBuffer("");
	
	public JPanel initPainelChat( final String usuario ){
		
		setChatLine( new JTextField() );
		// Set up the chat pane
	      setChatPane(new JPanel(new BorderLayout()));
	      setChatText(new JTextArea(10, 20));
	      getChatText().setLineWrap(true);
	      getChatText().setEditable(false);
	      getChatText().setForeground(Color.blue);
	      JScrollPane chatTextPane = new JScrollPane(getChatText(),
	         JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
	         JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

	      getChatLine().setEnabled( true );
	      
	      getChatLine().addActionListener( new ActionAdapter() {
	    	  
	            public void actionPerformed( ActionEvent e ) {
	            	
	               String s = getChatLine().getText();
	               
	               if ( !s.equals("") ) {
	                 	            	  	                  
	            	  getChatLine().selectAll();
	                  getChatLine().setText( "" );
	                  
	                  sendMessage( usuario + ": "+ s );
	               }
	            }
	         });
	      
	      getChatPane().add(getChatLine(), BorderLayout.SOUTH);
	      getChatPane().add(chatTextPane, BorderLayout.CENTER);
	      getChatPane().setPreferredSize( new Dimension(400, 400) );
	      
	      return getChatPane();
	}
	
	public PainelChat() {
		
	}
	
	public PainelChat( Socket cliente ) throws IOException {
		
		this.cliente = cliente;
		this.saida = new PrintStream( this.cliente.getOutputStream() );
	}
	
	public void sendMessage( String message ) {
		
		this.saida.println( message );
	}
	
	public JTextArea getChatText() {
		
		return chatText;
	}

	public void setChatText(JTextArea chatText) {
		
		this.chatText = chatText;
	}

	public JPanel getChatPane() {
		return chatPane;
	}

	public void setChatPane(JPanel chatPane) {
		this.chatPane = chatPane;
	}

	public PrintStream getSaida() {
		return saida;
	}

	public void setSaida(PrintStream saida) {
		this.saida = saida;
	}

	public JTextField getChatLine() {
		return chatLine;
	}

	public void setChatLine(JTextField chatLine) {
		this.chatLine = chatLine;
	}

	class ActionAdapter implements ActionListener {
		
	   public void actionPerformed( ActionEvent e ) {}
	}	
}
